import _ from 'lodash'
import File from '@/editor/common/js/workspace/file'
import ServiceClient from '@/editor/common/js/workspace/service-client'
import store from '@/store'
import { edgeReadFile } from '@/api/siddhi';
import { MessageBox } from "element-ui";
export default class Workspace {

    constructor(options) {
        this.app = store.getters.app
        this._serviceClient = new ServiceClient({ application: this.app });
    }
    onTabChange = function (evt) {
        this.updateMenuItems();
        var tab;
        if (app.tabController !== undefined) {
            tab = app.tabController.getTabFromId(evt.newActiveTab.cid);
        }
        if (evt.newActiveTab._title != "welcome-page") {
            if (tab.getSiddhiFileEditor() !== undefined) {
                tab.getSiddhiFileEditor().getSourceView().editorResize();
                tab.getSiddhiFileEditor().getSourceView().onEnvironmentChange();
            }
        }
        this.app.tabController.setActiveTab(tab);
        this.manageConsoles(evt);
    };

    createNewTab = function (options) {
        this.app = options.application
        this.app.tabController.newTab(options);
    };

    createNewETLFlowTab = function () {
        var editorId = app.config.container;
        var options = {};
        $(editorId).css("display", "block");
        //Showing menu bar
        _.set(options, "view", app.utils.getGlobalConstnts().VIEW_ETL_FLOW_WIZARD);
        app.tabController.newTab(options);
        app.outputController.makeInactiveActivateButton();
    };

    saveFileBrowserBased = function () {
        var editor = ace.edit('siddhi-editor');
        var code = editor.getValue();
        var filename = 'untitled';
        var match = plan_regex.exec(code);
        if (match && match[1]) {
            filename = match[1].replace(/ /g, '_');
        }
        var blob = new Blob([code], { type: 'text/plain;charset=utf-8' });
        saveAs(blob, filename + '.siddhi');
    };

    saveFile = function () {
        var editor = ace.edit('siddhi-editor');
        var code = editor.getValue();
        var filename = 'untitled';
        var match = plan_regex.exec(code);
        if (match && match[1]) {
            filename = match[1].replace(/ /g, '_') + '.siddhi';
        }
        var filePath = prompt('Enter a directory (absolute path) to save the siddhi app : ');
        filePath = (filePath.slice(-1) === '/') ? filePath + filename : filePath + '/' + filename;
        $.ajax({
            type: 'POST',
            url: window.location.protocol + '//' + window.location.host + '/editor/save',
            data: JSON.stringify({
                siddhiApp: code,
                filePath: filePath
            }),
            success: function (e) {
                alert('file successfully saved.');
            },
            error: function (e) {
                alert('failed to save file.');
            }
        });
    };

    handleSave = function (option) {
        var saveFileTab;
        if (option !== undefined && option.tabInstance !== undefined) {
            saveFileTab = option.tabInstance;
        } else {
            saveFileTab = app.tabController.getActiveTab();
        }
        var file = undefined;
        var siddhiFileEditor;
        var config = '';
        var providedAppName = '';
        var fileName = '';
        var options = {};
        if (saveFileTab != undefined) {//modify by chens

            if (saveFileTab.getTitle() != undefined && saveFileTab.getTitle() != "welcome-page") {//modify by chens
                file = saveFileTab.getFile();
            }

            if (file !== undefined) {
                if (file.isPersisted()) {
                    if (file.isDirty()) {
                        //var activeTab = app.tabController.activeTab;
                        var activeTab = saveFileTab;
                        siddhiFileEditor = activeTab.getSiddhiFileEditor();
                        config = siddhiFileEditor.getContent();
                        var response = self._serviceClient.writeFile(file, config);
                        if (response.error) {
                            alerts.error(response.message);
                            self.updateRunMenuItem();
                            return;
                        } else {
                            var trimmedSiddhiAppName = file.attributes.name;
                            if (checkEndsWithSiddhi(trimmedSiddhiAppName)) {
                                trimmedSiddhiAppName = trimmedSiddhiAppName.slice(0, -7);
                            }
                            app.commandManager.dispatch('remove-unwanted-streams-single-simulation',
                                trimmedSiddhiAppName);
                        }
                        if (file.getRunStatus() || file.getDebugStatus()) {
                            var launcher = activeTab.getSiddhiFileEditor().getLauncher();
                            launcher.stopApplication(app.workspaceManager, false);
                        }
                    }
                    if (!_.isNil(options) && _.isFunction(options.callback)) {
                        options.callback(true);
                    }
                } else {
                    options.tabInstance = saveFileTab;
                    options.utils = self.utils;
                    app.commandManager.dispatch('open-file-save-dialog', options);
                }
            }
            self.updateRunMenuItem();
        }
    };

    handleUndo = function () {

        // undo manager for current tab
        var undoManager = app.tabController.getActiveTab().getSiddhiFileEditor().getUndoManager();
        if (undoManager.hasUndo()) {
            undoManager.undo();
        }
        self.updateUndoRedoMenus();
    };

    handleRedo = function () {
        // undo manager for current tab
        var undoManager = app.tabController.getActiveTab().getSiddhiFileEditor().getUndoManager();
        if (undoManager.hasRedo()) {
            undoManager.redo();
        }
        self.updateUndoRedoMenus();
    };

    handleFind = function () {
        var activeTab = app.tabController.getActiveTab();

        if (activeTab.getTitle() != "welcome-page") {
            var aceEditor = app.tabController.getActiveTab().getSiddhiFileEditor().getSourceView().getEditor();
            aceEditor.execCommand('find');
        }
    };

    handleFindAndReplace = function () {
        var activeTab = app.tabController.getActiveTab();

        if (activeTab.getTitle() != "welcome-page") {
            var aceEditor = app.tabController.getActiveTab().getSiddhiFileEditor().getSourceView().getEditor();
            aceEditor.execCommand('replace');
        }
    };

    handleFormat = function () {
        if (app.tabController.getActiveTab().getTitle() !== "welcome-page") {
            if (app.tabController.getActiveTab().getSiddhiFileEditor().isInSourceView()) {
                app.tabController.getActiveTab().getSiddhiFileEditor().getSourceView().format();
            } else {
                app.tabController.getActiveTab().getSiddhiFileEditor().getDesignView().autoAlign();
            }
        }
    };

    handleRun = function (options) {
        var launcher = app.tabController.getActiveTab().getSiddhiFileEditor().getLauncher();
        launcher.runApplication(self);
    };

    handleSampleEvent = function (options) {
        if (_.isNil(this._sample_event_dialog)) {
            var opts = _.cloneDeep(_.get(app.config, 'sample_event_dialog'));
            _.set(opts, 'application', app);
            this._sample_event_dialog = new Dialogs.sample_event_dialog(opts);
        }
        // This dialog need to be re-rendered so that it comes on top of save file dialog.
        this._sample_event_dialog.render();
        this._sample_event_dialog.show();
    };

    handleStop = function (options) {
        var launcher = app.tabController.getActiveTab().getSiddhiFileEditor().getLauncher();
        if (options === undefined) {
            launcher.stopApplication(self, false);
        } else {
            launcher.stopApplication(self, options.initialLoad);
        }
    };

    handleDebug = function (options) {
        var launcher = app.tabController.getActiveTab().getSiddhiFileEditor().getLauncher();
        launcher.debugApplication(self);
    };

    openReplaceFileConfirmDialog = function (options) {
        if (_.isNil(this._replaceFileConfirmDialog)) {
            this._replaceFileConfirmDialog = new Dialogs.ReplaceConfirmDialog();
        }
        // This dialog need to be re-rendered so that it comes on top of save file dialog.
        this._replaceFileConfirmDialog.render();

        this._replaceFileConfirmDialog.askConfirmation(options);
    };

    updateMenuItems = function () {
        this.updateUndoRedoMenus();
        this.updateSaveMenuItem();
        this.updateExportMenuItem();
        this.updateRunMenuItem();
        this.updateDeleteMenuItem();
    };

    manageConsoles = function (evt) {
        if (app.outputController !== undefined) {
            app.outputController.showConsoleByTitle(evt.newActiveTab._title, "DEBUG");
            app.outputController.showConsoleByTitle(evt.newActiveTab._title, "FORM");
            //app.outputController.toggleOutputConsole();
        }
    };

    updateExportMenuItem = function () {
        var activeTab = app.tabController.getActiveTab(),
            exportMenuItem = app.menuBar.getMenuItemByID('file.export'),
            file = undefined;

        if (activeTab.getTitle() != "welcome-page") {
            file = activeTab.getFile();
        }

        if (file !== undefined) {
            var fileEditor = activeTab.getSiddhiFileEditor();
            if (fileEditor === undefined || fileEditor.isInSourceView()) {
                file = activeTab.getFile();
                if (file.isDirty()) {
                    exportMenuItem.disable();
                } else if (file.isPersisted()) {
                    exportMenuItem.enable();
                } else {
                    exportMenuItem.disable();
                }
            } else {
                exportMenuItem.disable();
            }
        } else {
            exportMenuItem.disable();
        }
    };

    updateUndoRedoMenus = function () {
        // undo manager for current tab
        var activeTab = app.tabController.getActiveTab(),
            undoMenuItem = app.menuBar.getMenuItemByID('edit.undo'),
            redoMenuItem = app.menuBar.getMenuItemByID('edit.redo'),
            findMenuItem = app.menuBar.getMenuItemByID('edit.find'),
            findAndReplaceMenuItem = app.menuBar.getMenuItemByID('edit.findAndReplace'),
            formatMenuItem = app.menuBar.getMenuItemByID('edit.format'),
            file = undefined;

        if (activeTab.getTitle() != "welcome-page") {
            file = activeTab.getFile();
        }

        if (file !== undefined) {
            var fileEditor = activeTab.getSiddhiFileEditor();
            if (!_.isUndefined(fileEditor)) {
                if (fileEditor.isInSourceView()) {
                    findMenuItem.enable();
                    findAndReplaceMenuItem.enable();
                    formatMenuItem.updateLabel('格式化代码');
                    formatMenuItem.enable();

                    var undoManager = fileEditor.getUndoManager();
                    if (undoManager.hasUndo() && undoManager.undoStackTop().canUndo()) {
                        undoMenuItem.enable();
                        undoMenuItem.addLabelSuffix(
                            undoManager.undoStackTop().getTitle());
                    } else {
                        undoMenuItem.disable();
                        undoMenuItem.clearLabelSuffix();
                    }
                    if (undoManager.hasRedo() && undoManager.redoStackTop().canRedo()) {
                        redoMenuItem.enable();
                        redoMenuItem.addLabelSuffix(
                            undoManager.redoStackTop().getTitle());
                    } else {
                        redoMenuItem.disable();
                        redoMenuItem.clearLabelSuffix();
                    }
                } else {
                    undoMenuItem.disable();
                    redoMenuItem.disable();
                    findMenuItem.disable();
                    findAndReplaceMenuItem.disable();
                    formatMenuItem.updateLabel('自动对齐');
                    formatMenuItem.enable();
                }
            }
        } else {
            undoMenuItem.disable();
            undoMenuItem.clearLabelSuffix();
            redoMenuItem.disable();
            redoMenuItem.clearLabelSuffix();
            findMenuItem.disable();
            findAndReplaceMenuItem.disable();
            formatMenuItem.disable();
        }
    };

    updateSaveMenuItem = function () {
        var activeTab = app.tabController.getActiveTab(),
            saveMenuItem = app.menuBar.getMenuItemByID('file.save'),
            saveAsMenuItem = app.menuBar.getMenuItemByID('file.saveAs'),
            file = undefined;

        if (activeTab.getTitle() != "welcome-page") {
            file = activeTab.getFile();
        }

        if (file !== undefined) {
            var fileEditor = activeTab.getSiddhiFileEditor();
            if (fileEditor === undefined || fileEditor.isInSourceView()) {
                file = activeTab.getFile();
                if (file.isDirty()) {
                    saveMenuItem.enable();
                    saveAsMenuItem.enable();
                } else {
                    saveMenuItem.disable();
                    saveAsMenuItem.enable();
                }
            } else {
                saveMenuItem.disable();
                saveAsMenuItem.disable();
            }
        } else {
            saveMenuItem.disable();
            saveAsMenuItem.disable();
        }
    };

    updateDeleteMenuItem = function () {
        var activeTab = app.tabController.getActiveTab(),
            deleteMenuItem = app.menuBar.getMenuItemByID('file.delete'),
            file = undefined;

        if (activeTab.getTitle() != "welcome-page") {
            file = activeTab.getFile();
        }

        if (file !== undefined) {
            file = activeTab.getFile();
            if (file.isPersisted()) {
                deleteMenuItem.enable();
            } else {
                deleteMenuItem.disable();
            }
        } else {
            deleteMenuItem.disable();
        }
    };

    updateRunMenuItem = function () {
        var activeTab = app.tabController.getActiveTab(),
            runMenuItem = app.menuBar.getMenuItemByID('run.run'),
            debugMenuItem = app.menuBar.getMenuItemByID('run.debug'),
            stopMenuItem = app.menuBar.getMenuItemByID('run.stop'),
            file = undefined;

        var toolBar = app.toolBar;

        if (activeTab.getTitle() != "welcome-page" && activeTab.getTitle() != "untitled") {
            file = activeTab.getFile();
        }

        if (file !== undefined) {
            var fileEditor = activeTab.getSiddhiFileEditor();
            if (fileEditor === undefined || fileEditor.isInSourceView()) {
                file = activeTab.getFile();
                if (file.isDirty()) {
                    runMenuItem.disable();
                    debugMenuItem.disable();
                    stopMenuItem.disable();
                    toolBar.disableRunButton();
                    toolBar.disableDebugButton();
                    toolBar.disableStopButton();
                    toolBar.enableRevertButton();
                } else {
                    toolBar.disableRevertButton();
                    if (file.getRunStatus() || file.getDebugStatus()) {
                        runMenuItem.disable();
                        debugMenuItem.disable();
                        stopMenuItem.enable();
                        toolBar.disableRunButton();
                        toolBar.disableDebugButton();
                        toolBar.enableStopButton();
                    } else if (!file.getRunStatus()) {
                        if (!file.getDebugStatus()) {
                            runMenuItem.enable();
                            debugMenuItem.enable();
                            stopMenuItem.disable();
                            toolBar.enableRunButton();
                            toolBar.enableDebugButton();
                            toolBar.disableStopButton();
                        } else {
                            stopMenuItem.enable();
                            toolBar.enableStopButton();
                        }
                    } else if (!file.getDebugStatus()) {
                        if (!file.getRunStatus()) {
                            runMenuItem.enable();
                            debugMenuItem.enable();
                            stopMenuItem.disable();
                            toolBar.enableRunButton();
                            toolBar.enableDebugButton();
                            toolBar.disableStopButton();
                        } else {
                            stopMenuItem.enable();
                            toolBar.enableStopButton();
                        }
                    }
                }
            } else {
                runMenuItem.disable();
                debugMenuItem.disable();
                toolBar.disableRunButton();
                toolBar.disableDebugButton();
                if (file.getRunStatus() || file.getDebugStatus()) {
                    stopMenuItem.enable();
                    toolBar.enableStopButton();
                } else {
                    stopMenuItem.disable();
                    toolBar.disableStopButton();
                }
            }
        } else {
            runMenuItem.disable();
            debugMenuItem.disable();
            stopMenuItem.disable();
            toolBar.disableRunButton();
            toolBar.disableDebugButton();
            toolBar.disableStopButton();
        }
    };

    updateExportArtifactsItem = function () {
        var exportMenuItem = app.menuBar.getMenuItemByID('export.export-for-docker'),
            exportKubeMenuItem = app.menuBar.getMenuItemByID('export.export-for-kubernetes'),
            deployToServerMenuItem = app.menuBar.getMenuItemByID('deploy.deploy-to-server');

        var savedFiles = app.workspaceExplorer.treeHeader.parent().find('div[id="folder-tree_-1"] > ul').children();
        if (savedFiles.length === 0) {
            exportMenuItem.disable();
            exportKubeMenuItem.disable();
            deployToServerMenuItem.disable();
        } else {
            exportMenuItem.enable();
            exportKubeMenuItem.enable();
            deployToServerMenuItem.enable();
        }
    };

    openFileSaveDialog = function openFileSaveDialog(options) {
        var activeTab = app.tabController.getActiveTab();
        if (activeTab != undefined) {//modify by chens
            if (_.isNil(this._saveFileDialog)) {
                this._saveFileDialog = new Dialogs.save_to_file_dialog(app);
            }
            if (options !== undefined && options.tabInstance !== undefined) {
                this._saveFileDialog.render(options.tabInstance);
            } else {
                this._saveFileDialog.render();
            }
            if (!_.isNil(options) && _.isFunction(options.callback)) {
                var isSaved = false;
                this._saveFileDialog.once('save-completed', function (success) {
                    isSaved = success;
                }, this);
                this._saveFileDialog.once('unloaded', function () {
                    options.callback(isSaved);
                }, this);
            }

            this._saveFileDialog.show();

            //                if (!_.isNil(activeTab) && _.isFunction(activeTab.getFile)) {
            //                    var activeFile = activeTab.getFile();
            //                    if (activeFile.isPersisted()) {
            //                        this._saveFileDialog.once('loaded', function() {
            //                            _saveFileDialog.setSelectedFile(activeFile.getPath(), activeFile.getName());
            //                        }, this);
            //                    }
            //                }
        }
    };

    handleDeploy = function handleDeploy(selectedFiles) {
        let opts = _.cloneDeep(app);
        opts.selectedFiles = selectedFiles || [];

        this._handleDeploy = new Dialogs.deploy_file_dialog(opts);
        this._handleDeploy.render();
        this._handleDeploy.show();
    };

    handleGenerateStreamDialog = function handleGenerateStreamDialog(ref, callback, streamObj) {
        if (!_.isNil(this._handleGenerateStreamDialog)) {
            _handleGenerateStreamDialog.clear();
        }
        this._handleGenerateStreamDialog = new Dialogs.generate_stream_dialog(app, ref, callback, streamObj);
        this._handleGenerateStreamDialog.render();
        this._handleGenerateStreamDialog.show();
    };

    handleExportForDocker = function handleExportForDocker(selectedFiles) {
        if (!_.isNil(this._handleExport)) {
            this._handleExport.clear();
        }

        let opts = _.cloneDeep(app);
        opts.selectedFiles = selectedFiles || [];
        opts.isExportDockerFlow = true;

        this._handleExport = new Dialogs.export_dialog(opts);
        this._handleExport.render();
        this._handleExport.show();
    };

    handleExportForKubernetes = function handleExportForKubernetes(selectedFiles) {
        if (!_.isNil(this._handleExport)) {
            this._handleExport.clear();
        }

        let opts = _.cloneDeep(app);
        app.selectedFiles = selectedFiles || [];
        opts.isExportDockerFlow = false;
        this._handleExport = new Dialogs.export_dialog(opts);
        this._handleExport.render();
        this._handleExport.show();
    };

    openDeleteFileConfirmDialog = function openDeleteFileConfirmDialog(options) {
        //if(options != undefined){ }//modify by chens
        if (_.isNil(this._deleteFileDialog)) {
            this._deleteFileDialog = new Dialogs.DeleteConfirmDialog(app);
        }
        this._deleteFileDialog.render(options);

        if (!_.isNil(options) && _.isFunction(options.callback)) {
            var isSaved = false;
            this._deleteFileDialog.once('save-completed', function (success) {
                isSaved = success;
            }, this);
            this._deleteFileDialog.once('unloaded', function () {
                options.callback(isSaved);
            }, this);
        }
        this._deleteFileDialog.show();

    };

    displayInitialTab = function () {
        // display first launch welcome page tab
        var tab = app.tabController.newTab({
            tabModel: {},
            tabOptions: { title: 'welcome-page' }
        });
        // Showing FirstLaunchWelcomePage instead of regularWelcomePage
        var opts = _.get(app.config, 'welcome');
        _.set(opts, 'application', app);
        _.set(opts, 'tab', tab);
        tab.getHeader().addClass('inverse')
        this.welcomePage = new WelcomePages.FirstLaunchWelcomePage(opts);
        this.welcomePage.render();
    };

    displayInitialWorkspace = function (app, fileName) {
        var activeTab_ = app.tabController.activeTab;//modefy by chens
        let path = 'workspace/' + fileName + '.siddhi';
        edgeReadFile(path).then(res => {
            if (res.status == 200) {
                var pathArray = _.split(path, app.getPathSeperator()),
                    fileName = _.last(pathArray),
                    folderPath = _.join(_.take(pathArray, pathArray.length - 1), app.getPathSeperator());

                var file = new File({
                    name: fileName,
                    path: folderPath,
                    content: res.data.content,
                    isPersisted: true,
                    isDirty: false
                });
                this.createNewTab({ app, tabOptions: { file: file } })
                // app.commandManager.dispatch("create-new-tab", {tabOptions: {file: file}});
            }
        }).catch(Error => {
            if (Error.response != undefined) {
                store.dispatch('siddhi/setLogData', { message: Error.response.data, type: 'ERROR' })
                store.dispatch('siddhi/setConsoleState', true)
            }
        })


    };
    passedFirstLaunch = function () {
        return app.browserStorage.get("pref:passedFirstLaunch") || false;
    };

    importFileImportDialog = function importFileImportDialog() {
        if (_.isNil(this._importFileDialog)) {
            this._importFileDialog = new Dialogs.import_file_dialog(app);
        }
        this._importFileDialog.render();
    };

    exportFileExportDialog = function exportFileExportDialog() {
        if (_.isNil(this._exportFileDialog)) {
            this._exportFileDialog = new Dialogs.export_file_dialog(app);
        }
        this._exportFileDialog.render();
    };

    handleExport = function (options) {
        var activeTab = app.tabController.getActiveTab();
        if (undefined != undefined) {//modify by chens
            var file = activeTab.getFile();
            if (!file.isDirty() && file.isPersisted()) {
                app.commandManager.dispatch('export-file-export-dialog', options);
            }
        }
    };

    openFileOpenDialog = function openFileOpenDialog() {
        if (_.isNil(this._openFileDialog)) {
            this._openFileDialog = new Dialogs.open_file_dialog(app);
        }
        this._openFileDialog.render();
        this._openFileDialog.show();
    };

    openSampleFileOpenDialog = function openSampleFileOpenDialog() {
        if (_.isNil(this._openSampleFileDialog)) {
            this._openSampleFileDialog = new Dialogs.open_sample_file_dialog(app);
        }
        this._openSampleFileDialog.render();
        this._openSampleFileDialog.show();
    };

    openExtensionInstallDialog = function openExtensionInstallDialog() {
        if (_.isNil(this._ExtensionInstallDialog)) {
            this._ExtensionInstallDialog = new Dialogs.ExtensionInstallDialog(app);
        }
        this._ExtensionInstallDialog.render();
        this._ExtensionInstallDialog.show();
    };

    openErrorHandlerDialog = function openErrorHandlerDialog() {
        if (_.isNil(this._errorHandlerDialog)) {
            this._errorHandlerDialog = new Dialogs.error_handler_dialog(app);
        }
        this._errorHandlerDialog.render();
        this._errorHandlerDialog.show();
    };

    openQueryStore = function openQueryStore(options) {
        if (_.isNil(this._queryStoreApi)) {
            var opts = _.cloneDeep(_.get(app.config, 'query_store_api'));
            _.set(opts, 'application', app);
            this._queryStoreApi = new Dialogs.query_store_api(opts);
        }
        this._queryStoreApi.render();
        this._queryStoreApi.show();
    };

    openCloseFileConfirmDialog = function (options) {
        if (_.isNil(this._closeFileConfirmDialog)) {
            this._closeFileConfirmDialog = new Dialogs.CloseConfirmDialog();
            this._closeFileConfirmDialog.render();
        }

        this._closeFileConfirmDialog.askConfirmation(options);
    };

    openCloseAllFileConfirmDialog = function (options) {
        if (_.isNil(this._closeAllFileConfirmDialog)) {
            this._closeAllFileConfirmDialog = new Dialogs.CloseAllConfirmDialog();
            this._closeAllFileConfirmDialog.render();
        }

        this._closeAllFileConfirmDialog.askConfirmation(options);
    };

    openSettingsDialog = function (options) {
        if (_.isNil(this._openSettingsDialog)) {
            var opts = _.cloneDeep(_.get(app.config, 'settings_dialog'));
            _.set(opts, 'application', app);
            this._openSettingsDialog = new Dialogs.settings_dialog(opts);
        }
        this._openSettingsDialog.render();
        this._openSettingsDialog.show();
    };

    closeAllTabs = function (options) {
        let that = this;
        let tabList = options.tabController.getTabList();
        let unSavedFileTabList = [];
        let savedFileTabList = [];
        _.each(tabList, function (tab) {
            if (tab != undefined) {
                if ((tab.state === 'new' && tab.isDirty == true) || (tab.state == 'old' && tab.isDirty == true)) {
                    unSavedFileTabList.push(tab)
                }
                if ((tab.state === 'new' && tab.isDirty == false) || (tab.state == 'old' && tab.isDirty == false)) {
                    savedFileTabList.push(tab)
                }
            }
        });

        _.each(savedFileTabList, function (tab) {
            options.tabController.removeTab(tab);
        });
        if (unSavedFileTabList.length != 0) {

            MessageBox.confirm("文件包含更改内容，是否要关闭它们 ? 如果关闭所有未保存的文件，你的更改内容将会丢失", "提示", {
                confirmButtonText: "关闭",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(() => {
                    _.each(unSavedFileTabList, function (tab) {
                        options.tabController.removeTab(tab);
                    });
                })
                .catch(() => {
                    that.$message({
                        type: "info",
                        message: "已取消",
                    });
                });
        }
    };

    closeTab = function (options) {
        let tabList = store.getters.ediEdgeTabs;
        let tabs = tabList.filter((item) => {
            return item.name == options.name
        })
        this.app.tabController.removeTab(tabs[0])
    };

    revertAppContent = function () {
        var tab = app.tabController.getActiveTab();
        var file = tab.getFile();
        if (file !== undefined && file.isDirty()) {
            var toolBar = app.toolBar;
            app.commandManager.dispatch('reload-file', tab.getTitle());
            toolBar.disableRevertButton();
            self.updateRunMenuItem();
        }
    };

    checkEndsWithSiddhi = function (string) {
        return string.endsWith('.siddhi');
    }

    runGuide = function () {
        log.debug("start: rendering hint guide");
        app.guide.startGuide();
        log.debug('end: rendering hint guide');
    };

    loadWorkspaceTree = async function () {
        var treeData = await this._serviceClient.loadWorkspaceTree();
        store.dispatch('siddhi/setTreeData', treeData)
    };

    runWorkspaceAPP = async function (json) {
        await this._serviceClient.runWorkspaceAPP(json);
    };

    stopWorkspaceAPP = async function (fileName) {
        await this._serviceClient.stopWorkspaceAPP(fileName);
    };
}

